<template>
  <div class="x_panel">
    <el-form :inline="true" :model="search" label-width="90px">
      <el-row>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createTime"
            style="width: 320px"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始"
            end-placeholder="结束"
          />
        </el-form-item>
        <el-form-item label="所属项目">
          <el-select
            v-model="search.itemCode"
            style="width: 100px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in projectList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动名称">
          <el-input
            v-model="search.activityTitle"
            style="width: 120px"
            placeholder="查询活动名称"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="search.activityStatus"
            style="width: 80px"
            placeholder="请选择"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动Code">
          <el-input
            v-model="search.activityCode"
            style="width: 120px"
            placeholder
          />
        </el-form-item>
        <!-- </el-row>
      <el-row> -->
        <el-form-item style="margin-left: 30px">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="query"
          >
            查询
          </el-button>
          <el-button icon="el-icon-plus" type="primary" @click="openAdd">
            创建活动
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-back"
            @click="backToProject"
          >
            返回项目列表
          </el-button>
        </el-form-item>
      </el-row>
    </el-form>
    <el-card v-loading="loading" class="box-card">
      <div v-if="tableData.length === 0" style="text-align: center">
        暂无活动
      </div>
      <div class="list">
        <el-table :data="tableData" border align="center" class="my_table">
          <el-table-column label="活动名称" prop="activityTitle" align="center" />
          <el-table-column label="缩略图" align="center">
            <template slot-scope="scope">
              <img
                class="img_inner"
                :src="scope.row.primaryPictureUrl ? scope.row.primaryPictureUrl : '/images/common/default.png'"
                @click="editItem(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.activityStatus === 0" style="color: green">线上</span>
              <span v-if="scope.row.activityStatus === 1" style="color: #666">未上线</span>
              <span v-if="scope.row.activityStatus === 2" style="color: red">已下线</span>
            </template>
          </el-table-column>
          <el-table-column label="创建人" prop="createdBy" align="center" />
          <el-table-column label="创建时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.dateCreated ? momentReturn(scope.row.dateCreated) : '暂无' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="上线时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.startTime ? momentReturn(scope.row.startTime) : '暂无' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="下线时间" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.endTime ? momentReturn(scope.row.endTime) : '暂无' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作上下线" align="center">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.onlineFlag"
                active-text="上线"
                inactive-text="下线"
                @change="changeStatus(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="400">
            <template slot-scope="scope">
              <el-button
                size="small"
                type="danger"
                @click="deleteItem(scope.row)"
              >
                删除
              </el-button>
              <el-button
                class="btn_YUP"
                type="primary"
                size="small"
                @click="editItem(scope.row)"
              >
                修改
              </el-button>
              <el-button
                size="small"
                class="btn_YUP"
                type="primary"
                @click="copyItem(scope.row)"
              >
                复制
              </el-button>
              <el-button
                size="small"
                class="btn_YUP"
                type="primary"
                @click="openLinkDialog(scope.row)"
              >
                查看链接
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <div v-if="pageShow" ref="pager" class="pager">
      <el-pagination
        background
        :current-page.sync="search.page"
        :page-size="search.length"
        layout="total,  prev, pager, next, jumper"
        :total="totalRows"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog width="80%" :visible.sync="linkDialog" title="活动链接查看">
      <el-form>
        <el-form-item label="推广链接" :label-width="formLabelWidth">
          <div style="display: flex">
            <el-input v-model="tglink" style="width: 80%" />&ensp;&ensp;
            <el-button id="tglink">
              复制
            </el-button>
          </div>

          <span style="color: red">用于发送短信等推广等营销场景</span>
        </el-form-item>
        <el-form-item label="活动链接" :label-width="formLabelWidth">
          <div style="display: flex">
            <el-input v-model="hdlink" style="width: 80%" />&ensp;&ensp;
            <el-button id="hdlink">
              复制
            </el-button>
          </div>
          <span style="color: red">用于APP内正常场景</span>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="linkDialog = false">
          关 闭
        </el-button>
        <!-- <el-button type="primary" @click="sureDd">确 定</el-button> -->
      </div>
    </el-dialog>

    <el-dialog
      title="活动上线"
      :visible.sync="publishDialogVisible"
      width="440px"
    >
      <el-date-picker v-model="sday" type="datetime" placeholder="选择开始时间" />

      到
      <el-date-picker v-model="eday" type="datetime" placeholder="选择结束时间" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="publishDialogVisible = false">取 消</el-button>
        <el-button
          :disabled="!sday || !eday"
          type="primary"
          @click="savePublish"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PageServer from '@/servers/page'
import Clipboard from 'clipboard'
import tool from '@/util/tool'
import { get, post } from '@/servers/http'
import { MOBILE_PAGE_HOST } from '@/config/default'
import moment from 'moment'
import Vue from 'vue'
import 'element-ui/lib/theme-chalk/index.css'
import ElementUI, { Loading } from 'element-ui'
Vue.use(ElementUI) 
Vue.use(Loading.directive)
export default {
  name: 'Activity',
  components: {
  },
  filters: {
    date: function (value) {
      if (!value || value === '') {
        return ''
      }
      let date = new Date(value)
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(), 
        'h+': date.getHours(), 
        'm+': date.getMinutes(), 
        's+': date.getSeconds(), 
        'q+': Math.floor((date.getMonth() + 3) / 3), 
        S: date.getMilliseconds(),
      }
      let fmt = 'yyyy-MM-dd hh:mm:ss'
      if (/(y+)/.test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + '').substr(4 - RegExp.$1.length)
        )
      for (let k in o)
        if (new RegExp('(' + k + ')').test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1
              ? o[k]
              : ('00' + o[k]).substr(('' + o[k]).length)
          )
      return fmt
    },
  },
  layout: 'manageLayout',
  data () {
    return {
      tglink: '',
      hdlink: '',
      cqlink: '',
      linkDialog: false,
      clipboardList: [],
      dialogLoading: false,
      publishDialogVisible:false,
      sday: null,
      eday: null,
      form: {
        ddtype: '1',
        ddUrlList: [{ url: '' }],
      },
      formLabelWidth: '80px',
      dialogFormVisible: false,
      tag: false,
      loading: false,
      createTime: [],
      statusList: [
        {
          label: '全部',
          value: null,
        },
        {
          label: '线上',
          value: 0,
        },
        {
          label: '未上线',
          value: 1,
        },
        {
          label: '已下线',
          value: 2,
        },
      ],
      projectList: [],
      pageShow: true,
      search: {
        activityCode: null,
        itemCode: '',
        startDate: null,
        endDate: null,
        activityStatus: null,
        activityTitle: null,
        start: 0,
        length: 20,
        page: 1,
      },
      totalRows: 0,
      // 表格数据
      tableData: [],
      projectName: '',
      editRow: {},
    }
  },
  computed: {},
  watch: {},
  mounted () {
    this.projectList = [
      { label: '全部', value: 'all' },
      {
        label: tool.getUrlParam('itemName'),
        value: tool.getUrlParam('itemCode'),
      },
    ]
    let from = tool.getUrlParam('from')
    if (from === 'child') {
      this.initFilters()
      this.renderDatble()
    } else {
      this.search.itemCode = tool.getUrlParam('itemCode')
      this.query()
    }
  },
  methods: {
    momentReturn (time) {
      return moment(time).format('YYYY-MM-DD HH:mm:ss')
    },
    openLinkDialog (item) {
      this.linkDialog = true
      let tempUrl = '/mobile?nativeStyle=hideNav&navStyle=light&gestureAble=Y&activityCode='
      this.tglink =
        this.$URLS.OUTER_MOBILE_PAGE_HOST + tempUrl + item.activityCode + '&t=' + new Date().getTime()
      this.hdlink =
        MOBILE_PAGE_HOST +
        tempUrl +
        item.activityCode + '&t=' + new Date().getTime()
      this.cqlink =
        MOBILE_PAGE_HOST +
        tempUrl +
        item.activityCode +
        '&client=cq' + '&t=' + new Date().getTime()
      this.initCopyItem([
        { id: 'tglink', url: this.tglink },
        { id: 'hdlink', url: this.hdlink },
        { id: 'cqlink', url: this.cqlink }
      ])
    },
    getItemName (title) {
      if (title) {
        let ext = title.length > 10 ? '…' : ''
        return title.substring(0, 8) + ext
      } else {
        return null
      }
    },
    addDdItem () {
      if (this.form.ddUrlList.length >= 5) {
        this.$message.error('最多只能添加5个地址！')
        return
      }
      this.form.ddUrlList.push({ url: '' })
    },
    deleteDdItem (item, index) {
      this.form.ddUrlList.splice(index, 1)
    },
    sureDd () {
      let _this = this
      if (this.form.ddtype === '2') {
        for (let i = 0; i < this.form.ddUrlList.length; i++) {
          let url = this.form.ddUrlList[i].url
          if (url === '') {
            this.$message.error(`第${i + 1}行地址不能为空！`)
            return
          }
        }
      } else {
        this.form.ddUrlList = []
      }
      _this.dialogLoading = true
      get(this.editRow.activityContent)
        .then((res) => {
          res.ddtype = _this.form.ddtype
          res.ddUrlList = _this.form.ddUrlList
          let requestUrl = '/activity/updateActivityInfoNew'
          let requestData = {
            itemCode: _this.editRow.itemCode,
            primaryPictureUrl: _this.editRow.primaryPictureUrl,
            activityTitle: _this.editRow.activityTitle,
            pageDot: _this.editRow.pageDot,
            activityContent: JSON.stringify(res),
            activityCode: _this.editRow.activityCode,
          }

          post(requestUrl, requestData).then((response) => {
            _this.dialogLoading = false
            if (response.flag === 'S') {
              _this.dialogFormVisible = false
              _this.$message({
                message: '保存成功',
                type: 'success',
              })
            } else {
              _this.$message.error('保存失败')
            }
          })
        })
        .catch(() => {
          _this.dialogLoading = false
        })
    },
    initCopyItem (list) {
      let _this = this
      // var list=[{id:'',url:''},{id:'',url:''}];
      for (let k = 0; k < _this.clipboardList.length; k++) {
        _this.clipboardList[k].destroy()
      }
      _this.clipboardList = []
      for (let i = 0; i < list.length; i++) {
        let itemId = list[i].id
        let url = list[i].url
        let clipboard = new Clipboard('#' + itemId, {
          text: function () {
            return url
          },
        })
        clipboard.on('success', () => {
          _this.$message({
            type: 'success',
            message: '复制成功!',
          })
        })
        clipboard.on('error', () => {
          console.log('该浏览器不支持自动复制')
        })
        _this.clipboardList.push(clipboard)
      }
    },
    getStatusName (item) {
      let status = this.statusList.find((a) => a.value === item.activityStatus)
      return status ? status.label : ''
    },
    backToProject () {
      location.href = '/management/project?from=child&shiro_sid='+tool.getUrlParam('shiro_sid')+'&token='+ tool.getUrlParam('token')
    },
    changeStatus (item) {
      this.editRow = item
      if (item.activityStatus !== 0){
        this.doOnline(item)
        item.onlineFlag = !item.onlineFlag
        return
      }
      this.$confirm('您正在执行活动下线操作，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.doOffline(item)
        })
        .catch(() => {
          item.onlineFlag = !item.onlineFlag
        })
    },
    doOffline(item){
      let requestData = {
        activityCode: item.activityCode,
        activityStatus: 2,
      }
      PageServer.changeStatusNew(requestData).then((res) => {
        if (res.flag === 'S') {
          // this.query()
          item.activityStatus=2
          item.published=1
          this.$message.info('活动下线成功！')
        }
      })
    },
    doOnline(){
      this.sday = moment().add(1, 'minutes')
      this.publishDialogVisible = true
    },
    savePublish () {
      if (!this.sday || !this.eday) {
        this.$message.error('请填写时间！')
        return
      }
      this.publishDialogVisible = false
      let data = {
        activityCode: this.editRow.activityCode,
        startDate: this.sday,
        endDate: this.eday,
      }
      if (
        new Date(data.startDate) < new Date() ||
        new Date(data.endDate) < new Date()
      ) {
        this.$message.error('时间不能小于当前时间！')
        return
      }
      if (
        new Date(data.startDate).getTime() > new Date(data.endDate).getTime()
      ) {
        this.$message.error('开始时间不能大于结束时间！')
        return
      }

      const transferData = {
        activityCode: this.editRow.activityCode,
        startDate: moment(this.sday).format('YYYY-MM-DD HH:mm:ss'),
        endDate: moment(this.eday).format('YYYY-MM-DD HH:mm:ss'),
      }

      post('/activity/publishNew', transferData).then((res) => {
        if (res.flag === 'S') {
          this.$message.info('活动上线成功！' )
          this.editRow.onlineFlag=true
          this.editRow.published=0
        } else {
          this.$message.error('上线失败：' + res.msg)
        }
      })
    },
    cancelPublish (item) {
      this.$confirm('您正在执行取消活动上线的操作，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.requestCancelPub(item)
        })
        .catch(() => {
           
        })
    },
    requestCancelPub(item){
      let requestData = {
        activityCode: item.activityCode,
        activityStatus: 2,
      }
      PageServer.changeStatusNew(requestData).then((res) => {
        if (res.flag === 'S') {
          item.published=1
          this.$message.info('活动已经取消上线！')
        }
      })
    },
    openAdd () {
      let activityCode = tool.guid()
      this.saveFilters()
      let url =`/management/creator?baseOn=0&activityCode=${activityCode}&type=0&project=${tool.getUrlParam('itemCode')}&itemName=${tool.getUrlParam('itemName') }&shiro_sid=${tool.getUrlParam('shiro_sid')}&token=${tool.getUrlParam('token')}`
      location.href =url   
    },
    configDdItem (row) {
      let _this = this
      _this.dialogLoading = true
      _this.form.ddtype = '1'
      this.editRow = row

      _this.dialogFormVisible = true
      get(this.editRow.activityContent + '?rand=' + tool.guid())
        .then((res) => {
          _this.dialogLoading = false
          _this.form.ddtype = res.ddtype ? res.ddtype : '1'
          _this.form.ddUrlList =
            res.ddUrlList && res.ddUrlList.length > 0
              ? res.ddUrlList
              : [{ url: '' }]
        })
        .catch(() => {
          _this.dialogLoading = false
        })
    },
    editItem (row) {
      let url =`/management/creator?baseOn=0&activityCode=${row.activityCode}&type=1&project=${row.itemCode}&itemName=${tool.getUrlParam('itemName') }&shiro_sid=${tool.getUrlParam('shiro_sid')}&token=${tool.getUrlParam('token')}`
      this.saveFilters()
      location.href = url
    },
    copyItem (row) {
      this.$confirm('您正在复制一个活动，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.requestCopyActivity(row)
      })
    },
    requestCopyActivity(row){
      PageServer.copyAcitivityNew({
        activityCode: row.activityCode,
        newActivityCode: tool.guid(),
      }).then((res) => {
        if (res.flag === 'S') {
          this.$message.info('复制成功！')
          this.search.page = 1
          this.renderDatble()
        }
      })
    },
    handleCurrentChange (val) {
      this.search.page = val
      this.renderDatble()
    },
    deleteItem (item) {
      this.$confirm('您正在删除该活动，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.saveDelete(item)
      })
    },
    saveDelete (item) {
      PageServer.deleteActivityInfo({
        activityCode: item.activityCode,
      }).then((res) => {
        if (res.flag === 'S') {
          this.$message.info('删除成功！')
          this.search.page = 1
          this.renderDatble()
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    saveFilters () {
      if (this.createTime && this.createTime.length === 2) {
        this.search.startDate = this.createTime[0]
        this.search.endDate = this.createTime[1]
      } else {
        this.search.startDate = null
        this.search.endDate = null
      }
      localStorage.setItem('activityFilters', JSON.stringify(this.search))
    },
    initFilters () {
      this.pageShow = false
      this.search = JSON.parse(localStorage.getItem('activityFilters'))
      if (this.search.startDate) {
        this.createTime = [
          new Date(this.search.startDate),
          new Date(this.search.endDate),
        ]
      }

      this.$nextTick(() => {
        this.pageShow = true
      })
    },
    renderDatble () {
      this.loading = true
      this.search.start = (this.search.page - 1) * this.search.length
      if (this.createTime && this.createTime.length === 2) {
        this.search.startDate = this.createTime[0]
        this.search.endDate = this.createTime[1]
        this.search.startTime = moment(this.createTime[0]).format('YYYY-MM-DD HH:mm:ss')
        this.search.endTime = moment(this.createTime[1]).format('YYYY-MM-DD HH:mm:ss')
      } else {
        this.search.startDate = null
        this.search.endDate = null
        this.search.startTime = null
        this.search.endTime = null
      }

      let filters = JSON.parse(JSON.stringify(this.search))
      if (filters.itemCode === 'all') {
        filters.itemCode = null
      }
      PageServer.queryActivityInfoList(filters).then((res) => {
        if (res.flag === 'S') {
          this.loading = false
          this.tableData = res.data.rows
          this.totalRows = res.data.total
          // this.initCopy(res.data.rows);
        }
      })
    },
    query () {
      this.search.start = 0
      this.search.page = 1
      this.renderDatble()
    },
  },
}
</script>


<style lang="less" scope>
.statistic-ico {
  position: relative;
  left: 94%;
  font-size: 18px;
  cursor: pointer;
}
.toolico {
  margin-left: 10px;
  font-size: 24px;
  cursor: pointer;
}
.online-color {
  background-color: #8dca35;
}
.wait-online-color {
  background-color: #ffba46;
}

.offline-color {
  background-color: #be8de9;
}

.cover-img {
  width: 260px;
  height: 356px;
}

.statusTag {
  position: relative;
  left: 100%;
  width: 52px;
  text-align: center;
  transform: translate(-62px, 0px);
  color: white;
  padding: 5px;
}
.box-card .list {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  margin-top: -10px;
}
.project-block {
  width: 25%;
  align-items: stretch;
  margin-top: 10px;
  display: flex;
}
.project-block .content {
  border: 1px solid #ccc;
  // margin: 10px
}

.c-pad {
  padding: 10px;
  overflow: hidden;
}
.project-block .content .text-block {
  padding: 10px;
}
.text-block .title {
  font-weight: bold;
  font-size: 20px;
  height: 30px;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-top: -24px;
}
.text-block .num {
  display: flex;
  flex-direction: row;
  padding: 10px 0px;
}
.text-block .num div {
  width: 50%;
}
.hd-table {
  display: flex;
  flex-direction: row;
  text-align: center;
}
.hd-table-block-first {
  border: 1px solid #ccc;
}
.hd-table-block {
  border: 1px solid #ccc;
  border-left: none;
}
.hd-table .cell {
  padding: 5px;
}
.up-box {
  border-bottom: 1px solid #ccc;
  background-color: #f8fbff;
}
.toolbar {
  font-size: 16px;
  // display: flex;
  // justify-content: flex-end;
  margin-top: 10px;
  margin-right: -10px;
  overflow: auto;
}
.toolbar i {
  padding: 0px 10px;
  cursor: pointer;
}
.toolbar .item {
  cursor: pointer;
  margin-top: 10px;
  float: left;
  margin-left: 10px;
}

.toolbar-block {
  display: flex;
  margin-top: 10px;
  justify-content: space-between;
}
.toolbar-block .layout {
  // width: 25%;

  
}

.toolbar-block .item {
  cursor: pointer;
}
.x_panel {
  background: #fff;
  padding: 20px;
  .theadbg {
    th {
      background: #f9f9f9;
    }
  }
  .tools-btn {
    margin-bottom: 10px;
  }
  .pager {
    margin-top: 10px;
    text-align: center;
  }
  .s1 {
    margin-right: 10px;
  }
}
.fullWindow {
  position: relative;
  width: 94% !important;
  top: 3%;
  left: 3%;
  height: 94%;
  margin: 0 !important;
  padding: 0 !important;
  z-index: 10;
  overflow: auto;
  > .el-dialog__header,
  .el-dialog__body,
  .x_panel {
    padding: 0;
  }
}
.null .el-message-box__message {
  padding-left: 0;
}
</style>

<style lang="less" scope>
.empty {
  height: 200px;
  line-height: 200px;
  text-align: center;
  color: #bbb;
  i {
    vertical-align: middle;
    font-size: 150px;
  }
}
.img_inner {
  width: 208px;
  height: 280px;
}
</style>
